package ui;

import java.awt.Toolkit;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.util.Calendar;

import network.NetworkVars;
import sun.audio.AudioPlayer;
import core.Phrox;
/**
 * This class will play sounds. However sun.audio.AudioPlayer
 *  can only play very specific sounds, therefore if
 *  more sounds are needed the init() method must be run.
 * @author jex
 *
 */
public class SoundPlayer {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		System.out.println(Calendar.getInstance().getTime());
		Toolkit.getDefaultToolkit();
		SoundPlayer sp = new SoundPlayer();
		sp.init();
		String file = "res/beep_1.au";
		file = "res/ni.au";
		File f = new File(file);
		sp.play(f.getAbsolutePath(),1000,2000);
		System.out.println("Done");
		System.out.println(Calendar.getInstance().getTime());
	}

	public boolean playing = false;
	public boolean special = false;
	public String cmd = null;

	public boolean init(){
		System.out.println("Initialising sound...");
		if(Phrox.os.contains("windows")){
			cmd = "res"+Phrox.fD+"SoundPlay.exe";
		}else if(Phrox.os.contains("linux")){
			cmd = "mplayer";
		}else if(Phrox.os.contains("mac")){
			cmd = "/usr/bin/afplay";
		}
		Runtime r = Runtime.getRuntime();
		Process p;
		try {
			p = r.exec(cmd);
			special = true;
			p.waitFor();
		} catch (IOException e) {
			//from the exec, it is the only fail case, all others count as success.
		} catch (Exception e) {
			e.printStackTrace();
		}
		if(!special){
			cmd = null;
			System.out.println("Will be using ");
		}else{
			System.out.println("Will be using '"+cmd+"' to play sounds.");
		}
		return special;
	}

	public boolean canPlay(){
		return !playing;
	}

	public void play(String str, long len, long tOut){
		play(new File(str),len,tOut);
	}

	public void play(File f, long len, long tOut){
		if(playing){
			return;
		}
		if(!f.exists()){
			System.out.println(f.getAbsolutePath()+" doesn't exist.");
			return;
		}
		playing = true;
		long start = System.currentTimeMillis();
		if(special){
			System.out.println("Playing '"+f.getAbsolutePath()+"' using '"+cmd+"'");
			//Use an Runtime.exec to play ANY sound file.
			String[] com = {cmd, f.getAbsolutePath()};
			Process p = null;
			try {
				p = Runtime.getRuntime().exec(com,null,new File(Phrox.rootDir));
				if(len < 0){
					while(len < 0 && !core.Util.timeLapsed(start, System.currentTimeMillis(), tOut) ){
						try {
							p.exitValue();
							break;
						} catch (Exception e) {}
						Thread.sleep(NetworkVars.defSleep);
					}
				}else{
					Thread.sleep(len);
				}
				p.destroy();
				p = null;
			} catch (IOException e) {
				System.err.println("Couldn't find one of : "+f.getAbsolutePath()+" or "+cmd);
			} catch (InterruptedException e) {
				e.printStackTrace();
			} finally {
				if(p != null){
					p.destroy();
				}
			}
		}else{
			System.out.println("Playing "+f.getAbsolutePath()+" using Native Java Code");
			try {
				InputStream s = new FileInputStream(f.getAbsolutePath());
				AudioPlayer.player.start(s);
				try {
					if(len < 0){
						while(len < 0 && AudioPlayer.player.isAlive()
								&& !core.Util.timeLapsed(start, System.currentTimeMillis(), tOut)){
							Thread.sleep(NetworkVars.defSleep);
						}
					}else{
						Thread.sleep(len);
					}
				} catch (InterruptedException e) {
					e.printStackTrace();
					System.err.println("Couldn't play sound "+f.getAbsolutePath()+" to completion");
				}
				AudioPlayer.player.stop(s);
			} catch (FileNotFoundException e1) {
				System.err.println("Couldn't find sound file: "+f.getAbsolutePath());
			}
		}
		playing = false;
		if( core.Util.timeLapsed(start, System.currentTimeMillis(), tOut) ){
			System.out.println("ui.SoundPlayer timed out on file:"+f.getAbsolutePath());
		}
	}

}
